scan = null; //扫描对象
mui.plusReady(function() {
	mui.init();
	startRecognize();
	plus.key.addEventListener('backbutton', function(){
		scan.close();
	});
});

//后退监听
function back() {
	history.back();
	scan.close();
}

//初始化扫描器
function startRecognize() {
	try {
		var filter;
		//自定义的扫描控件样式
		var styles = {
			frameColor: "#29E52C",
			scanbarColor: "#29E52C",
			background: ""
		}
		//扫描控件构造
		scan = new plus.barcode.Barcode('bcid', filter, styles);
		scan.onmarked = onmarked;
		scan.onerror = onerror;
		scan.start();
		//打开关闭闪光灯处理
		var flag = false;
		document.getElementById("turnTheLight").addEventListener('tap', function() {
			if(flag == false) {
				scan.setFlash(true);
				flag = true;
			} else {
				scan.setFlash(false);
				flag = false;
			}
		});
	} catch(e) {
		alert("出现错误啦:\n" + e);
	}
};

//打印错误信息
function onerror(e) {
	alert(e);
};

//二维码识别
function onmarked(type, result) {
	var text = '';
	switch(type) {
		case plus.barcode.QR:
			text = 'QR: ';
			break;
		case plus.barcode.EAN13:
			text = 'EAN13: ';
			break;
		case plus.barcode.EAN8:
			text = 'EAN8: ';
			break;
	}
	location.href = "../codeCheck/index.html?id="+result;
	scan.close();
};

// 手动输入优惠券码
function scanPicture() {
	scan.close();
	document.getElementById("demo1").style.setProperty("display", "none");
	mui.prompt("请输入优惠券号码", "确定", "手动输入优惠券", ["确定", "取消"], function(e) {
		if(e.index == 0) {
			var code = e.value;
			$.ajax({
				type: "get",
				url: BASE_URL + "/voucherInfo/getVoucherInfo",
				data: {
					"code":code
				},
				dataType: "json",
				xhrFields: {
					withCredentials: true
				},
				success: function(data) {
					var result = data.data;
					location.href = "../codeCheck/index.html?id="+result;

				}
		
			});
		} else {
			document.getElementById("demo1").style.setProperty("display", "block");
			startRecognize();
		}
	});

}